package org.socialresume.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.socialresume.client.model.FeedItem;
import org.socialresume.client.model.FeedTypeEnum;
import org.socialresume.client.model.TwitterFeed;
import org.socialresume.client.service.GreetingService;

import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	@Override
	public List<FeedItem> getTwitterUpdates(String twitterLogin, Long lastUpdateId) {
		Twitter twitter = new Twitter();
		try {
			List<Status> status = null;
			if(lastUpdateId != null){
				Paging paging = new Paging(lastUpdateId);
				status = twitter.getUserTimeline(twitterLogin,paging);
			}else{
				status = twitter.getUserTimeline(twitterLogin);
			}
			Logger.getLogger(GreetingServiceImpl.class.getName()).log(Level.WARNING,"Founded "+status.size()+" twitter update for "+twitterLogin);
			List<FeedItem> items = new ArrayList<FeedItem>();
			for (Status status2 : status) {
				FeedItem item = new FeedItem(status2.getId()+"", status2.getCreatedAt(), status2.getText());
				Map<String,String> infos = new HashMap<String, String>();
				infos.put(TwitterFeed.TwitterFeedInfoEnum.PROFIL_LOGO_URL.getKey(),status2.getUser().getProfileImageURL().toString());
				item.setInfos(infos);
				items.add(item);
			}
			return items;
		} catch (TwitterException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<FeedItem> getUpdates(FeedTypeEnum feedType, String feedUrl) {
		Logger.getLogger(GreetingServiceImpl.class.getName()).log(Level.WARNING,"Founded 0 update for "+feedUrl);
		return null;
	}
}
